﻿using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using AMM.CustomClassLibrary;
using AMM.Forms;

namespace AMM {
    static class Program {

        static Mutex mutex = new Mutex(true, "4d1c17d9-932c-4400-adba-ba2528fefe8f");
        [STAThread]
        static void Main() {
            if (mutex.WaitOne(TimeSpan.Zero, true)) {
                Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException);
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new FrmLogin());
                //Application.Run(new FrmTest());

                mutex.ReleaseMutex();
            }
            else {
                // send our Win32 message to make the currently running instance
                // jump on top of all the other windows
                NativeMethods.PostMessage(
                    (IntPtr)NativeMethods.HWND_BROADCAST,
                    NativeMethods.WM_SHOWME,
                    IntPtr.Zero,
                    IntPtr.Zero);
            }
        }

        static void OperateException(Exception ex) {
            string msg = MethodHelper.ExtractExceptionMessage(ex);
            Logger.Error(msg);
        }

        static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) {
            OperateException((Exception)e.ExceptionObject);
        }

        static void UIThreadException(object sender, ThreadExceptionEventArgs t) {
            OperateException(t.Exception);
        }
    }

    internal class NativeMethods {
        public const int HWND_BROADCAST = 0xffff;
        public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");
        [DllImport("user32")]
        public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
        [DllImport("user32")]
        public static extern int RegisterWindowMessage(string message);
    }
}
